<template>
  <div class="home">
    <el-container>
      <el-aside style="background-color: white">
        <el-scrollbar style="height: 620px; margin-top: 2px; margin-left: 2px">
          <el-tree
            :data="treeData"
            :default-checked-keys="rolemenu"
            @check-change="handleCheckChange"
            @node-click="handleNodeClick"
            :expand-on-click-node="true"
            :accordion="true"
           ref="tree"
            show-checkbox
            node-key="MenuCode"
          >
            <span slot-scope="{ node, data }">
              &nbsp;&nbsp;{{ node.label }}
            </span>
          </el-tree>
        </el-scrollbar>
      </el-aside>
      <el-container>
        <el-header
          style="
            left: 0px;
            top: 0px;
            width: 100%;
            right: 0;
            z-index: 5;
            margin-top: 0;
            text-align: left;
          "
        >
          <el-form
            ref="form"
            :model="form"
            :inline="true"
            size="mini"
            class="Seach"
            style="float: left"
            label-position="left"
          >
            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-check"
                size="small"
                @click="confirmData"
                >保存</el-button
              >
            </el-form-item>
          </el-form>
        </el-header>

        <el-main>
          <el-table
            :data="Datelist"
            style="width: 100%; margin-top: 0px"
            border
            :height="tableHeight"
          >
            <el-table-column align="center" label="序号" width="60">
              <template slot-scope="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="ID" width="110" v-if="false">
              <template slot-scope="scope">
                {{ scope.row.ID }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="菜单编码">
              <template slot-scope="scope">
                {{ scope.row.MenuCode }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="按钮">
              <template slot-scope="scope">
                {{ scope.row.ButtonName }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="启用">
              <template slot-scope="scope">
                <el-checkbox-group v-model="ButtonCode">
                  <el-checkbox :label="scope.row.ButtonCode" @change="handleButtonChange"></el-checkbox>
                </el-checkbox-group>
              </template>
            </el-table-column>
          </el-table>
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script>
import path from "path";
import { deepClone } from "@/utils";
import {
  getDataList,
  updateUserRoleMapData,
  updateRoleRightMapData,
} from "@/api/System";

export default {
  props: {
    inputName: String,
    required: true,
  },

  data() {
    return {
      tableHeight: null,
      ProjectForm: "",
      routes: [],
      menu: [],
      rolemenu: [], //提交数据
      treeData: [],
      Datelist: [],
      ButtonCode: [], //提交数据
      Search: {
        // 查询条件
        total: 0, // 总记录数
        pageSize: 0, // 一页显示的记录数
        page: 1, // /当前页码
        RNO: "009", // 表编号
        jsWhere: "", // 自定义条件
      },
      SearchRoleMenu: {
        // 查询条件
        total: 0, // 总记录数
        pageSize: 0, // 一页显示的记录数
        page: 1, // /当前页码
        RNO: "010", // 表编号
        jsWhere: "", // 自定义条件
      },
      SearchMenuButton: {
        // 查询条件
        total: 0, // 总记录数
        pageSize: 0, // 一页显示的记录数
        page: 1, // /当前页码
        RNO: "011", // 表编号
        jsWhere: "", // 自定义条件
      },
      SearchRMenuButton: {
        // 查询条件
        total: 0, // 总记录数
        pageSize: 0, // 一页显示的记录数
        page: 1, // /当前页码
        RNO: "012", // 表编号
        jsWhere: "", // 自定义条件
      },

      screenWidth: document.body.clientWidth,
    };
  },
  computed: {
    routesData() {
      return this.routes;
    },
  },
  created() {
    this.getDataList();
  },
  mounted() {
    setTimeout(() => {
      this.tableHeight = window.innerHeight - 340 + "px";
    });
  },

  methods: {
    async getDataList() {
      // 获取列表数据，通用
      this.Search.AppCode = "A05"; //系统编码
      this.Search.IsVisible = 1; //菜单可见
      this.Search.IsEnable = 1; //菜单启用
      const res = await getDataList({ data: JSON.stringify(this.Search) });
      this.SearchRoleMenu.jsWhere =" and RoleCode='"+this.inputName+"'"; //角色
      const resRM = await getDataList({
        data: JSON.stringify(this.SearchRoleMenu),
      });
      this.menu = res.data.Table;
      var rolemenulist = [];
      resRM.data.Table.forEach((r) => {
        rolemenulist.push(r.MenuCode);
      });
      this.rolemenu = rolemenulist;
      this.actionGetCatalog();
    },
    actionGetCatalog() {
      let data = this.menu;
      for (let i = 0; i < data.length; i++) {
        //把"MenuName"换成"label"
        data[i].label = data[i].MenuName;
        delete data[i].MenuName;
      }
      this.treeData = this.getJsonTree(data, {
        id: "MenuCode",
        pid: "ParentCode",
        children: "children",
      });
    },
    //将json（一般从后台获取）转成jsonTree格式 参考文档：https://blog.csdn.net/unamattin/article/details/77152451
    getJsonTree(data, config) {
      let id = config.id || "id",
        pid = config.pid || "pid",
        children = config.children || "children";
      let idMap = [],
        jsonTree = [];
      data.forEach(function (v) {
        idMap[v[id]] = v;
      });
      data.forEach(function (v) {
        let parent = idMap[v[pid]];
        if (parent) {
          !parent[children] && (parent[children] = []);
          parent[children].push(v);
        } else {
          jsonTree.push(v);
        }
      });
      return jsonTree;
    },
    //点击节点加载角色菜单
    async handleNodeClick(data) {
      //一级菜单不加载角色按钮
      if (
        data.ParentCode != "0" &&
        data.ParentCode != "" &&
        data.ParentCode != null
      ) {
        this.SearchMenuButton.MenuCode = data.MenuCode;
        const res = await getDataList({
          data: JSON.stringify(this.SearchMenuButton),
        });
        this.SearchRMenuButton.RoleCode = this.inputName;
        this.SearchRMenuButton.MenuCode = data.MenuCode;
        const resRole = await getDataList({
          data: JSON.stringify(this.SearchRMenuButton),
        });
        var buttonlist = [];
        resRole.data.Table.forEach((r) => {
          buttonlist.push(r.ButtonCode);
        });
        this.Datelist = res.data.Table;
        this.ButtonCode = buttonlist;
      }
    },
    //选中菜单节点
    handleCheckChange(data, checked, indeterminate) {
      if (checked == true) {
        this.rolemenu.push(data.MenuCode)
      } else {
        var index=(data.MenuCode)
        this.rolemenu.splice(index,1)
      }

      

     
    },

    async confirmData() {
      // 提交数据，需要修改
    
     let res = this.$refs.tree.getCheckedKeys().concat(this.$refs.tree.getHalfCheckedKeys());


      const result = await updateRoleRightMapData({
        RolemenuList: JSON.stringify(res),
        ButtonCodeList: JSON.stringify(this.ButtonCode),
        RoleCode: this.inputName,
        MenuCode: this.SearchRMenuButton.MenuCode,
        IsPostBack: true,
      });

      if (result.code === 20000) {
        this.$notify({
          title: "Success",
          dangerouslyUseHTMLString: true,
          message: result.msg,
          type: "success",
        });
       
      } else {
        this.$notify({
          title: "error",
          dangerouslyUseHTMLString: true,
          message: result.msg,
          type: "error",
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  .EditObjs-table {
    margin-top: 30px;
  }

  .permission-tree {
    margin-bottom: 5px;
  }
}
</style>
